﻿using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;

using NewLife.Log;
using NewLife.Serialization;

using RestSharp;

using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private string _BASE_URL = $"https://mom.hisense.com";

        private void Form1_Load(object sender, EventArgs e)
        {
            CreateWebView2();
        }

        private WebView2 webView;

        private async Task<bool> InitializeWebView2()
        {
            try
            {
                string version = CoreWebView2Environment.GetAvailableBrowserVersionString();
                return !string.IsNullOrEmpty(version);
            }
            catch
            {
                // 引导用户安装 WebView2 Runtime
                MessageBox.Show("WebView2 Runtime 未安装。请安装后重试。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        public async Task CreateWebView2()
        {
            if (!await InitializeWebView2())
            {
                return;
            }

            webView = new WebView2();
            webView.Dock = DockStyle.Fill;
            Controls.Add(webView);

            var pangeaTokenInfo = await GetTokenAsync();

            if ("0".Equals(pangeaTokenInfo?.code) && !string.IsNullOrWhiteSpace(pangeaTokenInfo?.data?.access_token))
            {
                //var targetUrl = $"{_BASE_URL}/mom_pc/r_andon_pcba/andon/dashboard/explore?access_token={pangeaTokenInfo.data.access_token}";

                var targetUrl = $"{_BASE_URL}/mom_pc/agentUserDetails?token={pangeaTokenInfo.data.access_token}";

                XTrace.WriteLine($"[targetUrl:{targetUrl}]");

                await InitializeWebView2Async(targetUrl);
            }
            else
            {
                XTrace.WriteLine($"[mom token fail:{pangeaTokenInfo.ToJson()}]");
            }
        }

        private async Task<PangeaData<TokenInfo>> GetTokenAsync()
        {
            // 创建 RestClient 实例，指定请求的基础 URL
            var client = new RestClient(_BASE_URL);

            // 创建一个 POST 请求
            var request = new RestRequest("/api/auth/token/getPangeaTokenByLdap", Method.Post);

            // 添加请求参数
            request.AddJsonBody(new
            {
                systemName = "mom",
                value = "zhuokelu.ex"
            });

            PangeaData<TokenInfo> result = null;
            try
            {
                // 执行请求
                var response = await client.ExecuteAsync(request);

                // 检查响应状态
                if (response.IsSuccessful)
                {
                    Console.WriteLine("请求成功");
                    Console.WriteLine("响应内容: " + response.Content);

                    result = Newtonsoft.Json.JsonConvert.DeserializeObject<PangeaData<TokenInfo>>(response.Content);
                }
                else
                {
                    Console.WriteLine("请求失败");
                    Console.WriteLine("错误信息: " + response.ErrorMessage);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("发生异常: " + ex.Message);
            }

            return result;
        }

        private async Task InitializeWebView2Async(string url)
        {
            var tempPath = Path.GetTempPath();
            var appTempDir = Path.Combine(tempPath, "WebView2");

            var env = await CoreWebView2Environment.CreateAsync(null, appTempDir);
            await webView.EnsureCoreWebView2Async(env);
            webView.CoreWebView2.Navigate(url);
        }
    }

    public class PangeaData<T>
    {
        public long ts { get; set; }
        public T data { get; set; }
        public string code { get; set; }
        public string msg { get; set; }
        public string alert { get; set; }
    }

    public class TokenInfo
    {
        public string access_token { get; set; }
        public string token_type { get; set; }
        public string refresh_token { get; set; }
        public int expires_in { get; set; }
        public int user_id { get; set; }
        public string username { get; set; }
        public string loginName { get; set; }
    }

}
